package com.topboya.linker.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.topboya.linker.AppConst;
import com.topboya.linker.R;
import com.topboya.linker.diyview.group.GroupRecyclerAdapter;
import com.topboya.linker.model.levelitem.SelectDeviceGroup;
import com.topboya.linker.model.levelitem.SelectProductGroup;
import com.topboya.linker.model.response.LatelyDataResponse;
import com.topboya.linker.model.response.NewlyOrgListResponse;
import com.topboya.linker.model.response.OrganizationResopnse;
import com.topboya.linker.model.response.ProductInforListReponse;
import com.topboya.linker.model.response.SelectFileResponse;
import com.topboya.linker.ui.activity.SellectProductInforActivity;
import com.topboya.linker.ui.activity.xSelectFileActivity;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class SelectProductAdapter extends GroupRecyclerAdapter<String,SelectProductGroup> {

    private static final String TAG = "SelectProductAdapter:";
    private SellectProductInforActivity mContext;
    private ArrayList<ProductInforListReponse.ProductDetailInfoList> groupList;
    private ArrayList<LatelyDataResponse.Data> newlyList;
    private List<SelectProductGroup> allProductGroups;
//   用来保存被选中的对象
    private LinkedHashMap<String,SelectProductGroup>  mSelectedPositions = new LinkedHashMap<>();

    public SelectProductAdapter(Context context, ArrayList<ProductInforListReponse.ProductDetailInfoList> groupList, ArrayList<LatelyDataResponse.Data> newlyList) {

        super(context);
        this.mContext = (SellectProductInforActivity) context;
        this.groupList = groupList;
        this.newlyList = newlyList;
        allProductGroups= new ArrayList<>();
    }


    //获得选中条目的结果
    public ArrayList<SelectProductGroup> getSelectedItem() {

        ArrayList<SelectProductGroup> selectList = new ArrayList<>();
        for(Map.Entry<String,  SelectProductGroup> entry : mSelectedPositions.entrySet()) {

            SelectProductGroup productDetailInfoList = entry.getValue();
            selectList.add(productDetailInfoList);
        }
        return selectList;
    }

    public ArrayList<ProductInforListReponse.ProductDetailInfoList> selectAllorunSelectAll(boolean isChecked){
//        将所有的条目变为选中状态
        ArrayList<ProductInforListReponse.ProductDetailInfoList> selectList = new ArrayList<>();
        if (isChecked){

            for (int i=0;i <allProductGroups.size();i++){

                if (null ==mSelectedPositions.get(allProductGroups.get(i).getId())){

                    mSelectedPositions.put(allProductGroups.get(i).getId(),allProductGroups.get(i));
                }
            }
        }else {

            for (int i=0;i <allProductGroups.size();i++){

               mSelectedPositions.remove(allProductGroups.get(i).getId());

            }
        }
        notifyDataSetChanged();
        return selectList;

    }


    @Override
    protected RecyclerView.ViewHolder onCreateDefaultViewHolder(ViewGroup parent, int type) {

        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.select_product_item, parent, false);
        return new SelectProductAdapter.ListItemViewHolder(itemView);

    }

    //绑定界面，设置监听

    @Override
    protected void onBindViewHolder(RecyclerView.ViewHolder holder, SelectProductGroup item, int i) {
        LogUtils.v(TAG + "onBindViewHolder()"+"position:"+i);
        ListItemViewHolder h = (ListItemViewHolder)holder;

        //设置条目状态
        h.tv_productName.setText(item.getProductName());
        int isvisible =Integer.parseInt(item.getFileNum()) > 0 ? View.VISIBLE : View.GONE;
        h.img_data.setVisibility(isvisible);
        h.tv_productcompany.setText(item.getProductFactory());
        if (null !=item.getFileLists() && item.getFileLists().size() > 0){

            h.tv_select_file_num.setVisibility(View.VISIBLE);
            h.tv_select_file_num.setText(String.valueOf(item.getFileLists().size()));

        }else {

            h.tv_select_file_num.setVisibility(View.INVISIBLE);
        }


        if (null !=isItemChecked(i)){

            h.tv_productName.setTextColor(mContext.getResources().getColor(R.color.home_bottom_text_checked));

//           如果不为空，则说明产品以前是被选中的状态，直接从linkedhashmap中获取，这样就可以将产品也设置上去
            SelectProductGroup  productDetailInfoListtemp = mSelectedPositions.get(allProductGroups.get(i).getId());
            if (null != productDetailInfoListtemp.getFileLists() && productDetailInfoListtemp.getFileLists().size() >0){

                h.tv_select_file_num.setVisibility(View.VISIBLE);
                h.tv_select_file_num.setText(String .valueOf(productDetailInfoListtemp.getFileLists().size()));

            }else {

                h.tv_select_file_num.setVisibility(View.INVISIBLE);
            }
        }else {
            h.tv_productName.setTextColor(Color.BLACK);

        }


        //条目view的监听
        h.itemView.setOnClickListener(v -> {

           SelectProductGroup  productDetailInfoList = allProductGroups.get(i);
            LogUtils.v(TAG + "SelectProductGroup:"+productDetailInfoList.getProductName());

            h.tv_productName.setTextColor(mContext.getResources().getColor(R.color.home_bottom_text_checked));

            if (null !=isItemChecked(i)) {

                productDetailInfoList = mSelectedPositions.get(allProductGroups.get(i).getId());
                if (null !=productDetailInfoList.getFileLists() && productDetailInfoList.getFileLists().size()>0){

                    UIUtils.showToast("请先取消已选择的产品资料信息");
                    return;
                }
                setItemUnChecked(productDetailInfoList.getId());
                h.tv_productName.setTextColor(Color.BLACK);

            } else {

                setItemChecked(productDetailInfoList.getId(),productDetailInfoList);
                h.tv_productName.setTextColor(mContext.getResources().getColor(R.color.home_bottom_text_checked));

            }
//           notifyItemChanged(i);
            int count = getSelectedItem().size();
            itemClickListener.onClick(holder.itemView ,i,count);

        });

        h.img_data.setOnClickListener(v1 -> {

           SelectProductGroup  productDetailInfoList = allProductGroups.get(i);
            setItemChecked(productDetailInfoList.getId(),productDetailInfoList);
            h.tv_productName.setTextColor(mContext.getResources().getColor(R.color.home_bottom_text_checked));

            int count = getSelectedItem().size();
            itemClickListener.onClick(holder.itemView ,i,count);
//            ArrayList<ProductInforListReponse.ProductDetailInfoList> productDetailInfoLists = getSelectedItem();
            Intent intent = new Intent(mContext,xSelectFileActivity.class);
//            将点点击的位置传过去，回来如果需要更新数据直接更新数据，不用遍历
            intent.putExtra("position",String.valueOf(i));
            intent.putExtra("productId",allProductGroups.get(i).getId());
//            intent.putExtra("productDetailInfoLists",productDetailInfoLists);
            intent.putExtra("fileLists",allProductGroups.get(i).getFileLists());
            mContext.startActivityForResult(intent,1000);

        });

    }



    //设置给定位置条目的选择状态
    public void setItemChecked(String id,SelectProductGroup productDetailInfoList) {

        mSelectedPositions.put(id,productDetailInfoList);
    }
    //设置给定位置条目的选择状态
    public void setItemUnChecked(String id) {

        mSelectedPositions.remove(id);
    }


//    设置产品选中的资料数
    public void setSelectFileList(ArrayList<SelectFileResponse.FileList> fileLists){

        for (SelectFileResponse.FileList file:fileLists){

             mSelectedPositions.get(file.getProductId());
       }

    }

    //根据位置判断条目是否选中
    private SelectProductGroup isItemChecked(int position) {

        return mSelectedPositions.get(allProductGroups.get(position).getId());
    }


//    @Override
//    public int getItemCount() {
//
//        return allProductGroups == null ? 0 : allProductGroups.size();
//    }

    public class ListItemViewHolder extends RecyclerView.ViewHolder{

        //ViewHolder
        TextView tv_productName;
        TextView tv_productcompany;
        ImageView img_data;
        TextView tv_select_file_num;

        ListItemViewHolder(View view) {
            super(view);
            this.tv_productName = view.findViewById(R.id.tv_productName);
            this.tv_productcompany = view.findViewById(R.id.tv_productcompany);
            this.img_data = view.findViewById(R.id.img_data);
            this.tv_select_file_num = view.findViewById(R.id.tv_select_file_num);

        }

    }

    private SelectProductAdapter.OnItemClickListener itemClickListener;

    public void setOnItemClickListener(SelectProductAdapter.OnItemClickListener itemClickListener){

        this.itemClickListener = itemClickListener;
    }

    public interface  OnItemClickListener{

        void onClick(View v,int position,int count);
    }


    private List<SelectProductGroup> create(int p) {

        List<SelectProductGroup> list = new ArrayList<>();
        if (p == 0) {
            for (int i=0;i < newlyList.size();i++){
//                LogUtils.v(TAG +"groupList.get(i).getOrgName():"+groupList.get(i).getOrgName());
                SelectProductGroup selectProductGroup = new SelectProductGroup();
                selectProductGroup.setProductName(newlyList.get(i).getProductName());
                selectProductGroup.setId(newlyList.get(i).getId());
                selectProductGroup.setProductFactory(newlyList.get(i).getProductFactory());
                selectProductGroup.setFileNum(newlyList.get(i).getFileNum());
                list.add(selectProductGroup);

            }

        } else if (p == 1) {

            for (int i = 0; i < groupList.size(); i++) {

                SelectProductGroup selectProductGroup = new SelectProductGroup();
                selectProductGroup.setProductName(groupList.get(i).getProductName());
                selectProductGroup.setId(groupList.get(i).getId());
                selectProductGroup.setProductFactory(groupList.get(i).getProductFactory());
                selectProductGroup.setFileNum(groupList.get(i).getFileNum());
                list.add(selectProductGroup);

            }
        }

        return list;
    }

    public void resetGroups() {

        LinkedHashMap<String, List<SelectProductGroup>> map = new LinkedHashMap<>();
        List<String> titles = new ArrayList<>();
        map.put("★ 最近", create(0));
        map.put("全部", create(1));
        titles.add("★ 最近");
        titles.add("全部");
//        将不同类型组成放到同一个数据里面，条目点击事件需要，可能框架有好的方法
        resetGroups(map,titles);

    }

    public void setItemData(List<SelectProductGroup> selectProductGroups ){

        this.allProductGroups = selectProductGroups;
        LogUtils.v(TAG +"allProductGroups:"+allProductGroups.size());
    }
}
